<script setup>
import { ref, onMounted } from 'vue'
import { getMyJoinedAccompany, getMyCreatedAccompany, auditAccompanyApply, getAccompanyAuditList } from '@/api/accompany'
import { showToast, showDialog } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref(0)
const joinedList = ref([])
const createdList = ref([])
const loading = ref(false)
const showAuditPopup = ref(false)
const auditList = ref([])

const loadJoinedAccompany = async () => {
  try {
    loading.value = true
    const res = await getMyJoinedAccompany()
    joinedList.value = res.data.records
  } catch (error) {
    showToast('获取参加的结伴失败')
  } finally {
    loading.value = false
  }
}

const loadCreatedAccompany = async () => {
  try {
    loading.value = true
    const res = await getMyCreatedAccompany()
    createdList.value = res.data.records
  } catch (error) {
    showToast('获取发布的结伴失败')
  } finally {
    loading.value = false
  }
}

const handleAudit = async (memberId, approved) => {
  try {
    await showDialog({
      title: '确认',
      message: `确定要${approved ? '通过' : '拒绝'}该申请吗？`,
      showCancelButton: true
    })
    
    await auditAccompanyApply(memberId, approved)
    showToast(`${approved ? '通过' : '拒绝'}成功`)
    
    // 更新本地数据状态
    const targetAudit = auditList.value.find(item => item.id === memberId)
    if (targetAudit) {
      targetAudit.status = approved ? 1 : 2
    }
  } catch (error) {
    if (error?.message !== '取消') {
      showToast('操作失败')
    }
  }
}

const showAuditList = async (id) => {
  try {
    const res = await getAccompanyAuditList(id)
    auditList.value = res.data
    showAuditPopup.value = true
  } catch (error) {
    showToast('获取申请记录失败')
  }
}

onMounted(() => {
  loadJoinedAccompany()
})

const onTabChange = (index) => {
  if (index === 1 && createdList.value.length === 0) {
    loadCreatedAccompany()
  }
}
</script>

<template>
  <div class="my-accompany">
    <van-nav-bar title="我的结伴" left-arrow @click-left="$router.back()" />
    
    <van-tabs v-model:active="activeTab" @change="onTabChange">
      <van-tab title="我参加的">
        <van-pull-refresh v-model="loading" @refresh="loadJoinedAccompany">
          <div class="accompany-list">
            <van-empty v-if="!loading && joinedList.length === 0" description="暂无参加的结伴" />
            
            <div v-else v-for="item in joinedList" :key="item.id" class="accompany-card">
              <div class="card-header">
                <div class="title">{{ item.title }}</div>
                <div class="status" :class="item.status === 0 ? 'active' : 'closed'">
                  {{ item.status === 0 ? '进行中' : '已结束' }}
                </div>
              </div>
              
              <div class="info-row">
                <van-icon name="location" />
                <span>{{ item.destination }}</span>
              </div>
              
              <div class="info-row">
                <van-icon name="friends" />
                <span>{{ item.currentMembers }}/{{ item.maxMembers }}人</span>
              </div>
              
              <div class="info-row">
                <van-icon name="clock" />
                <span>{{ item.startTime.split('T')[0] }} 至 {{ item.endTime.split('T')[0] }}</span>
              </div>
              
              <div class="actions">
                <van-button 
                  type="primary" 
                  size="small"
                  @click="router.push(`/accompany/${item.id}`)"
                >
                  查看详情
                </van-button>
              </div>
            </div>
          </div>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="我发布的">
        <van-pull-refresh v-model="loading" @refresh="loadCreatedAccompany">
          <div class="accompany-list">
            <van-empty v-if="!loading && createdList.length === 0" description="暂无发布的结伴" />
            
            <div v-else v-for="item in createdList" :key="item.id" class="accompany-card">
              <div class="card-header">
                <div class="title">{{ item.title }}</div>
                <div class="status" :class="item.status === 0 ? 'active' : 'closed'">
                  {{ item.status === 0 ? '进行中' : '已结束' }}
                </div>
              </div>
              
              <div class="info-row">
                <van-icon name="location" />
                <span>{{ item.destination }}</span>
              </div>
              
              <div class="info-row">
                <van-icon name="friends" />
                <span>{{ item.currentMembers }}/{{ item.maxMembers }}人</span>
              </div>
              
              <div class="info-row">
                <van-icon name="clock" />
                <span>{{ item.startTime.split('T')[0] }} 至 {{ item.endTime.split('T')[0] }}</span>
              </div>
              
              <div class="actions">
                <van-button 
                  type="primary" 
                  size="small"
                  @click="router.push(`/accompany/${item.id}`)"
                >
                  查看详情
                </van-button>
                <template v-if="item.status === 0">
                  <van-button 
                    type="primary" 
                    size="small"
                    @click="showAuditList(item.id)"
                  >
                    查看申请记录
                  </van-button>
                </template>
              </div>
            </div>
          </div>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    
    <van-popup
      v-model:show="showAuditPopup"
      round
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div class="audit-popup">
        <div class="popup-header">
          <h3>申请记录</h3>
        </div>
        <div class="audit-list">
          <div v-for="audit in auditList" :key="audit.id" class="audit-item">
            <div class="user-info">
              <img :src="audit.user.avatar" class="avatar">
              <div class="info">
                <div class="username">{{ audit.user.username }}</div>
                <div class="uid">ID: {{ audit.user.uid }}</div>
                <div class="email">{{ audit.user.email }}</div>
              </div>
            </div>
            <div class="status">
              <span :class="[
                'status-tag',
                audit.status === 0 ? 'pending' : 
                audit.status === 1 ? 'approved' : 'rejected'
              ]">
                {{ audit.status === 0 ? '待审核' : (audit.status === 1 ? '已通过' : '已拒绝') }}
              </span>
            </div>
            <div class="actions" v-if="audit.status === 0">
              <van-button 
                type="success" 
                size="small"
                @click="handleAudit(audit.id, true)"
              >
                通过
              </van-button>
              <van-button 
                type="danger" 
                size="small"
                @click="handleAudit(audit.id, false)"
              >
                拒绝
              </van-button>
            </div>
          </div>
          <van-empty v-if="auditList.length === 0" description="暂无申请记录" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
.my-accompany {
  min-height: 100vh;
  background: #f8f8f8;
  
  .accompany-list {
    padding: 16px;
    
    .accompany-card {
      background: white;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        .title {
          font-size: 16px;
          font-weight: 500;
        }
        
        .status {
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          
          &.active {
            background: rgba(25, 137, 250, 0.1);
            color: #1989fa;
          }
          
          &.closed {
            background: rgba(150, 151, 153, 0.1);
            color: #969799;
          }
        }
      }
      
      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        color: #666;
        font-size: 14px;
        
        .van-icon {
          margin-right: 6px;
          font-size: 16px;
        }
      }
      
      .actions {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        margin-top: 12px;
        
        .van-button {
          min-width: 80px;
        }
      }
    }
  }
}

.audit-popup {
  padding: 20px;
  
  .popup-header {
    text-align: center;
    margin-bottom: 20px;
    
    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .audit-list {
    .audit-item {
      background: #f8f8f8;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 12px;
      
      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        
        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-right: 12px;
        }
        
        .info {
          .username {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .uid, .email {
            font-size: 14px;
            color: #666;
          }
        }
      }
      
      .status {
        color: #666;
        margin-bottom: 12px;
      }
      
      .actions {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
      }
    }
  }
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  
  &.pending {
    background: rgba(25, 137, 250, 0.1);
    color: #1989fa;
  }
  
  &.approved {
    background: rgba(62, 175, 124, 0.1);
    color: #3eaf7c;
  }
  
  &.rejected {
    background: rgba(245, 108, 108, 0.1);
    color: #f56c6c;
  }
}
</style>